<template>
    <a-modal :keyboard="false" :maskClosable="false" title="字典编辑" :open="visible" :width="700" :confirmLoading="loading" centered @ok="handleSubmit" @cancel="handleCancel">
        <a-form layout="vertical">
            <a-form-item label="父级名称" v-bind="validateInfos.label" v-if="modelRef.parentId">
                <a-input v-model:value="modelRef.parentName" disabled />
            </a-form-item>
            <a-form-item label="字典名称" v-bind="validateInfos.name">
                <a-input v-model:value="modelRef.name" />
            </a-form-item>
            <a-form-item label="字典编码" v-bind="validateInfos.type">
                <a-input v-model:value="modelRef.type" :disabled="+modelRef.id > 0" />
            </a-form-item>
            <a-form-item label="描述" v-bind="validateInfos.remark" v-if="modelRef.parentId">
                <a-input v-model:value="modelRef.remark" />
            </a-form-item>
            <a-form-item label="排序" v-if="modelRef.parentId">
                <a-input-number v-model:value="modelRef.sort" />
            </a-form-item>
            <a-form-item label="状态" v-bind="validateInfos.status" v-if="modelRef.parentId">
                <a-radio-group v-model:value="modelRef.status">
                    <a-radio :value="1">启用</a-radio>
                    <a-radio :value="0">禁用</a-radio>
                </a-radio-group>
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script lang="ts">
    import type { PropType } from 'vue';
    import { defineComponent, reactive, ref, watchEffect, watch } from 'vue';
    import { Form, message } from 'ant-design-vue';
    import type { DictDataParams } from '@/api/user/dict';
    import { createDictData, updateDictData, createDictType, updateDictType, getDictData, getDictType } from '@/api/user/dict';
    import { cloneDeep, isUndefined } from 'lodash-es';

    const formLayout = {
        labelCol: {
            xs: { span: 24 },
            sm: { span: 7 },
        },
        wrapperCol: {
            xs: { span: 24 },
            sm: { span: 13 },
        },
    };

    export default defineComponent({
        props: {
            visible: {
                type: Boolean,
                required: true,
            },
            model: {
                type: Object as PropType<DictDataParams | null>,
                default: () => null,
            },
        },
        emits: ['cancel', 'success'],
        setup(props, { emit }) {
            const loading = ref(false);
            const modelRef = reactive<any>({
                status: 1,
                parentId: 0,
            });
            const rulesRef = reactive({
                name: [{ required: true, message: '请输入字典名称' }],
                type: [{ required: true, message: '请输入字典编码' }],
            });
            const { validateInfos, resetFields, validate } = Form.useForm(modelRef, rulesRef);

            // 记录初始值
            const initValues = reactive({});
            watch(
                () => props.visible,
                () => {
                    Object.assign(initValues, cloneDeep(props.model));
                },
            );
            watchEffect(() => {
                if (props.visible) {
                    if (props.model) {
                        console.log(props.model);

                        Object.assign(modelRef, props.model);
                        // 这一步可以不用，直接传递 model.permissions 到页面进行渲染
                        // 这里重新组装是为了演示结构不相同情况下可以按照下列方案组装结构
                        // (isUndefined(modelRef.parentId) ? getDictData : getDictType).then(res => {
                        //     if (!isEmpty(res.data)) {
                        //         const { id, status, name, type, label, value, dict } = res.data;
                        //     }
                        // });
                    } else {
                        // 没有传递 model 属于新增
                    }
                }
            });

            const handleCancel = () => {
                resetFields();
                Object.keys(modelRef).forEach(key => {
                    delete modelRef[key];
                });
                emit('cancel');
            };

            const handleSubmit = async () => {
                validate().then(() => {
                    loading.value = true;
                    const { name, type, status, id, parentId, dictType, sort } = modelRef;
                    const params: any = {
                        status,
                    };
                    if (!isUndefined(parentId) && parentId != 0) {
                        params.label = name;
                        params.value = type;
                        params.sort = sort;
                        params.dictType = dictType;
                    } else {
                        params.name = name;
                        params.type = type;
                    }

                    if (!isUndefined(id)) {
                        params.id = id;
                    }

                    (isUndefined(id)
                        ? isUndefined(parentId) || parentId == 0
                            ? createDictType
                            : createDictData
                        : isUndefined(parentId) || parentId == 0
                        ? updateDictType
                        : updateDictData)(params)
                        .then(res => {
                            if (res.data) {
                                message.success('操作成功');
                                emit('success');
                                handleCancel();
                            }
                        })
                        .finally(() => {
                            loading.value = false;
                        });
                });
            };
            return {
                ...formLayout,

                loading,

                modelRef,
                validateInfos,
                resetFields,

                handleSubmit,
                handleCancel,

                initValues,
            };
        },
    });
</script>
